<template>
  <el-popover ref="popover"
              placement="bottom-start"
              trigger="click"
              class="tree__select">
    <div class="tree_wrap" @click="$refs.input.focus()">
      <el-tree
        ref="tree"
        class="select-tree"
        highlight-current
        :data="data"
        :props="props"
        :lazy="lazy"
        :load="load"
        @node-click="onClickNode"
      >
        <span class="custom-tree-node" slot-scope="{ node }">{{ node.label }}</span>
      </el-tree>
    </div>
    <el-input
      suffix-icon="el-icon-arrow-down"
      slot="reference"
      ref="input"
      v-model="labelModel"
      :class="{ 'rotate': showStatus }"
      :placeholder="placeholder"
      :disabled="disabled"
    ></el-input>
  </el-popover>
</template>
<script>
export default {
  props: {
    placeholder: String,
    // 是否可选
    disabled: Boolean,
    // 当前选中节点
    value: String,
    // 树菜单数据
    data: Array,
    /** 配置项
      * @param {String, Function(data, node)} label 指定节点标签为节点对象的某个属性值
      * @param {String} children children	指定子树为节点对象的某个属性值
      * @param {Boolean, Function(data, node)} disabled 指定节点选择框是否禁用为节点对象的某个属性值
      * @param {Boolean, Function(data, node)} isLeaf 指定节点是否为叶子节点，仅在指定了 lazy 属性的情况下生效
    */
    props: {
      type: Object,
      default: {
        label: 'label',
        children: 'children'
      }
    },
    // 是否懒加载子节点，需要配合load 方法使用
    lazy: {
      type: Boolean,
      default: false
    },
    // 加载子树数据的方法，仅当 lazy 属性为true 时生效 function(node, function)
    load: Function,
    // 树状菜单被点击
    clickNodeCallback: Function
  },
  data() {
    return {
      // 树菜单是否显示
      showStatus: false
    }
  },
  computed: {
    labelModel: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  },
  methods: {
    // 树状菜单被点击
    onClickNode(node) {
      if (this.clickNodeCallback && this.clickNodeCallback(node)) this.$refs.popover.showPopper = false;
    },
    // 通过key 查询 label
    queryTree(tree, key) {
      let stark = [];
      stark = stark.concat(tree);
      while (stark.length) {
        const temp = stark.shift();
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children]);
        }
        if (temp[this.props.value] === key) {
          return temp[this.props.label];
        }
      }
      return "";
    },
  }
};
</script>
<style lang="scss" scoped>
  @import '@/styles/mixin.scss';
  .tree_wrap {
    height: 200px;
    width: 400px;
    @include scrollBar;
  }
</style>
